/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.hualu.zks.GUI;

import com.hualu.zks.Model.User;
import com.hualu.zks.Dao.UserDao;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Administrator
 */
public class JFrame_UserManagerAdmin extends javax.swing.JDialog {

    /**
     * Creates new form userManager
     */
    JFrame parent;
    
    public JFrame_UserManagerAdmin(JFrame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.parent=parent;
//        System.out.println(getUserList.get(0).getUserName());
//        System.out.println(getUserList.size());
        RefreshUserList();
        //隐藏id列
        userListShow.getColumnModel().getColumn(0).setMinWidth(0);
        userListShow.getColumnModel().getColumn(0).setMaxWidth(0);
    }

    public final void RefreshUserList() {
        ArrayList<User> getUserList = UserDao.getUserList();
        int rowCount = ((DefaultTableModel) userListShow.getModel()).getRowCount();
        //删除表里之前内容
        for (int i = rowCount - 1; i >= 0; i--) {
            ((DefaultTableModel) userListShow.getModel()).removeRow(i);
        }
        //更新表格内容
//        for (int i = 0; i < plist.size(); i++) {
        for (User plist1 : getUserList) {//1.6里新加的foreach方法
            Vector vector = new Vector();
            vector.add(plist1.getUserId());
            vector.add(plist1.getUserName());
            vector.add(plist1.getUserPwd());
            ((DefaultTableModel) userListShow.getModel()).addRow(vector);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        userListPanel = new javax.swing.JScrollPane();
        userListShow = new javax.swing.JTable();
        addBtn = new javax.swing.JButton();
        editBtn = new javax.swing.JButton();
        delBtn = new javax.swing.JButton();
        backBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("用户管理");
        setIconImage(Toolkit.getDefaultToolkit().getImage("pic\\bfhl.jpg"));
        setResizable(false);
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        userListShow.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id", "用户名", "密码"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        userListShow.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        userListShow.setShowHorizontalLines(false);
        userListPanel.setViewportView(userListShow);
        if (userListShow.getColumnModel().getColumnCount() > 0) {
            userListShow.getColumnModel().getColumn(0).setResizable(false);
            userListShow.getColumnModel().getColumn(0).setPreferredWidth(0);
        }

        addBtn.setText("增加");
        addBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addBtnActionPerformed(evt);
            }
        });

        editBtn.setText("修改");
        editBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editBtnActionPerformed(evt);
            }
        });

        delBtn.setText("删除");
        delBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delBtnActionPerformed(evt);
            }
        });

        backBtn.setText("返回");
        backBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(27, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(34, 34, 34)
                        .addComponent(editBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(delBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(33, 33, 33)
                        .addComponent(backBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(userListPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(userListPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addBtn)
                    .addComponent(editBtn)
                    .addComponent(delBtn)
                    .addComponent(backBtn))
                .addGap(31, 31, 31))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backBtnActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
        parent.setVisible(true);
    }//GEN-LAST:event_backBtnActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        parent.setVisible(true);
    }//GEN-LAST:event_formWindowClosing

    private void delBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delBtnActionPerformed
        // TODO add your handling code here:
        if (userListShow.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(null, "请先选择一条信息！", "警告", JOptionPane.WARNING_MESSAGE);
        } else {
            String userId = String.valueOf(userListShow.getValueAt(userListShow.getSelectedRow(), 0));
            String userName = String.valueOf(userListShow.getValueAt(userListShow.getSelectedRow(), 1));

            //ok 0,否 1,取消 2
            int ret = JOptionPane.showConfirmDialog(null, "确认删除用户：" + userName + "?", "提示", JOptionPane.OK_CANCEL_OPTION);
            System.out.println("ret!:" + ret + "");
            if (ret == 0) {
                System.out.println("userId:" + userListShow.getValueAt(userListShow.getSelectedRow(), 0));//获得选中行的第一列的数据
                if ("1".equals(userId)) {
                    JOptionPane.showMessageDialog(null, "管理员账户不可以删除!", "警告", JOptionPane.WARNING_MESSAGE);
                    RefreshUserList();
                } else {
                    if (UserDao.delUser(userId)) {
                        JOptionPane.showMessageDialog(null, "删除成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
                        RefreshUserList();
                    } else {
                        JOptionPane.showMessageDialog(null, "删除失败!", "警告", JOptionPane.WARNING_MESSAGE);
                        RefreshUserList();
                    }
                }
            }
        }
    }//GEN-LAST:event_delBtnActionPerformed

    private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addBtnActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
        new JFrame_UserAdd(this, rootPaneCheckingEnabled).setVisible(true);
    }//GEN-LAST:event_addBtnActionPerformed

    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
        // TODO add your handling code here:
        RefreshUserList();
    }//GEN-LAST:event_formWindowGainedFocus

    private void editBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editBtnActionPerformed
        // TODO add your handling code here:
        if(userListShow.getSelectedRow()==-1){
            JOptionPane.showMessageDialog(null, "请先选择一条信息！", "警告", JOptionPane.WARNING_MESSAGE);
        }else{
            String userId = String.valueOf(userListShow.getValueAt(userListShow.getSelectedRow(), 0));
            String userName = String.valueOf(userListShow.getValueAt(userListShow.getSelectedRow(), 1));
            String userPwd = String.valueOf(userListShow.getValueAt(userListShow.getSelectedRow(), 2));
            new JFrame_UserEdit(this, rootPaneCheckingEnabled, userId, userName, userPwd).setVisible(true);
        }
    }//GEN-LAST:event_editBtnActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrame_UserManagerAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrame_UserManagerAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrame_UserManagerAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrame_UserManagerAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame_UserManagerAdmin dialog = new JFrame_UserManagerAdmin(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addBtn;
    private javax.swing.JButton backBtn;
    private javax.swing.JButton delBtn;
    private javax.swing.JButton editBtn;
    private javax.swing.JScrollPane userListPanel;
    private javax.swing.JTable userListShow;
    // End of variables declaration//GEN-END:variables
}
